package edu.suda.LoopCodePlus.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import edu.suda.LoopCodePlus.common.Result;
import edu.suda.LoopCodePlus.entity.SubmissionRecord;
import edu.suda.LoopCodePlus.service.SubmissionService;
import edu.suda.LoopCodePlus.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/submission")
@Slf4j
public class SubmissionController {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private SubmissionService submissionService;
    @GetMapping("/get")
    public Result get(@RequestParam("problemId") Integer problemId,
                      HttpServletRequest request,
                      HttpServletResponse response) {
        System.out.println("验证token");
        String token = request.getHeader("Authorization");
        Integer userId;
        try {
            DecodedJWT decodedJWT = jwtUtil.verifyToken(token);
            userId = Integer.parseInt(decodedJWT.getClaim("userId").asString());
            System.out.println("token验证成功");
        }catch (Exception e){
            System.out.println("token验证失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return null;
        }
        System.out.println("参数验证");
        if(problemId==null){
            return Result.failure("参数错误");
        }
        System.out.println("参数验证通过");
        try{
            System.out.println("查找"+problemId+"题目的提交记录");
            List<SubmissionRecord> submissionRecords = submissionService.findSubmissionRecordById(userId,problemId);
            System.out.println("查找成功:\n"+submissionRecords);
            return Result.success(submissionRecords);
        }catch (Exception e){
            System.out.println("查找失败");
            return Result.failure("查找失败");
        }
    }
}
